<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Hash;

class AdminUser extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'username',
        'email',
        'name',
        'phone',
        'password',
        'role',
        'status',
        'last_login_at',
        'last_login_ip'
    ];

    protected $hidden = [
        'password',
        'remember_token'
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'last_login_at' => 'datetime'
    ];

    protected $dates = ['deleted_at'];

    // 关联权限
    public function permissions()
    {
        return $this->belongsToMany(AdminPermission::class, 'admin_role_permissions', 'role', 'permission_id', 'role', 'id');
    }

    // 关联操作日志
    public function operationLogs()
    {
        return $this->hasMany(AdminOperationLog::class);
    }

    // 关联身份切换日志
    public function impersonationLogs()
    {
        return $this->hasMany(AdminImpersonationLog::class);
    }

    // 关联创建的租户
    public function createdTenants()
    {
        return $this->hasMany(Tenant::class, 'created_by');
    }

    // 用户角色常量
    const ROLE_SUPER_ADMIN = 'super_admin';     // 超级管理员
    const ROLE_ADMIN = 'admin';                 // 管理员
    const ROLE_OPERATOR = 'operator';           // 操作员
    const ROLE_VIEWER = 'viewer';               // 查看员

    // 用户状态常量
    const STATUS_ACTIVE = 'active';             // 激活
    const STATUS_INACTIVE = 'inactive';         // 停用
    const STATUS_LOCKED = 'locked';             // 锁定

    // 获取角色显示名称
    public function getRoleDisplayAttribute()
    {
        $roles = [
            self::ROLE_SUPER_ADMIN => '超级管理员',
            self::ROLE_ADMIN => '管理员',
            self::ROLE_OPERATOR => '操作员',
            self::ROLE_VIEWER => '查看员'
        ];

        return $roles[$this->role] ?? $this->role;
    }

    // 获取状态显示名称
    public function getStatusDisplayAttribute()
    {
        $statuses = [
            self::STATUS_ACTIVE => '激活',
            self::STATUS_INACTIVE => '停用',
            self::STATUS_LOCKED => '锁定'
        ];

        return $statuses[$this->status] ?? $this->status;
    }

    // 设置密码
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    // 检查是否有指定权限
    public function hasPermission($permission)
    {
        if ($this->role === self::ROLE_SUPER_ADMIN) {
            return true;
        }

        return $this->permissions()->where('name', $permission)->exists();
    }

    // 检查是否有身份切换权限
    public function canImpersonate()
    {
        return $this->hasPermission('tenant.impersonate');
    }

    // 更新最后登录信息
    public function updateLastLogin($ip = null)
    {
        $this->last_login_at = now();
        $this->last_login_ip = $ip;
        $this->save();
    }
}